package com.sys.controller;

import com.sys.entity.SysLog;
import com.sys.utils.MongodbUtils;
import com.sys.utils.Utils;
import com.bhudy.utils.ResponseResult;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Pattern;

/**
 * @Author bhudy
 * @Description SysLogController
 * @Date Wed Nov 13 17:45:49 CST 2019
 */
@RestController
public class SysMongoDBLogController {

    /**
     * 获取操作日志的的数据
     *
     * @param page  页数{1}
     * @param limit 显示数量{10}
     * @return sysLog的list
     */
    @GetMapping(value = "/api/v1/sysMongoDBLogs")
    public ResponseResult getAll(Integer page, Integer limit, String requestUrl, Integer logType, String time) {
        if (page == null) page = 1;
        if (limit == null) limit = 10;
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("_id"))).limit(limit).skip(--page * limit);
        if (requestUrl != null && !requestUrl.equals("")) {
            query.addCriteria(Criteria.where("requestUrl").regex(Pattern.compile("^.*" + requestUrl + ".*$", Pattern.CASE_INSENSITIVE)));
        }
        if (logType != null && logType > -1) {
            query.addCriteria(Criteria.where("logType").gt(logType));
        }
        if (time != null && !time.equals("")) {
            query.addCriteria(Criteria.where("createDate")
                    .lt(Utils.formatDate(Utils.formatLong(time.split(",")[0])))
                    .gte(Utils.formatDate(Utils.formatLong(time.split(",")[1]))));
        }
        return ResponseResult.printMapJson(0, MongodbUtils.mongoTemplate.count(query, SysLog.class), MongodbUtils.mongoTemplate.find(query, SysLog.class));
    }

    @GetMapping(value = "/api/v1/sysMongoDBLog")
    public ResponseResult get(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").gt(new ObjectId(id)));
        return ResponseResult.printMapJson(0, MongodbUtils.mongoTemplate.findOne(query, SysLog.class));
    }

    /*@PostMapping(value = "/api/v1/sysMongoDBLog")
    public ResponseResult insert(@RequestBody String json) {
        return ResponseResult.printMapJson(0, sysLogService.insert(JSONObject.parseObject(json, SysLog.class)));
    }

    @PutMapping(value = "/api/v1/sysMongoDBLog")
    public ResponseResult update(@RequestBody String json) {
        return ResponseResult.printMapJson(0, sysLogService.update(JSONObject.parseObject(json, SysLog.class)));
    }

    @DeleteMapping(value = "/api/v1/sysMongoDBLog")
    public ResponseResult delete(@RequestBody String json) {
        return ResponseResult.printMapJson(0, sysLogService.delete(JSONObject.parseObject(json, String[].class)));
    }*/

}
